package slowtime

import (
	"time"
)

func M每X毫秒整点(每X毫秒 int, handler func(), afterHandler func(difTime time.Duration)) {

	time.Sleep(time.Duration(计算误差时间(time.Now(), int64(每X毫秒))))
	//fmt.Println("M每毫秒整点", time.Now().Format("2006-01-02 15:04:05.999999999"))
	for {
		prevTime := time.Now()
		if handler != nil {
			handler()
		}
		afterTime := time.Now()
		if afterHandler != nil {
			afterHandler(afterTime.Sub(prevTime))
		}
		time.Sleep(time.Duration(计算误差时间(afterTime, int64(每X毫秒))))
		//fmt.Println("M每毫秒整点", time.Now().Format("2006-01-02 15:04:05.999"))
	}
}

func 计算误差时间(now time.Time, 每X毫秒 int64) int {
	dif := now.UnixNano() - (now.UnixMilli()/每X毫秒)*int64(time.Millisecond)*每X毫秒
	sleepTime := int64(time.Millisecond)*每X毫秒 - dif
	if sleepTime < 0 {
		sleepTime = 0
	}
	return int(sleepTime)
}
